/**
 * @author zhangqiang
 * @data 2017/3/14
 *  地址列表
 * karin 修改 2017/07/14
 * */
/**
 * Karin on 20170720
 * 年检支付后，用户地址列表
 */
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {Toast} from 'antd-mobile'
import style from './index.scss'
import PageBar from '../../components/common/pageBar'
import Address from '../../components/addressList'
import AlipayJSOperation from '../../utils/alipayJSOperation'

import getDataService from '../../services/getData'

import SendCxytjMessage from '../../utils/sendCxytjMessage'

class AddressList extends Component {
    constructor(props) {
        super(props)

        this.state = {
            type: localStorage.getItem('addressList_action') || 0, //默认选中
            dataList: [], //地址列表
        }
        this.orderId = this.props.params.orderId; // carId
        this.payTypeData = this.props.params.type // 默认寄送类型.person个人；ems邮政
    }


    /**
     * 生命周期
     */
    componentWillMount() {

    }

    componentWillUnmount() {
        AlipayJSOperation.removeLeftButtonEvent();
    }


    componentDidMount() {
        document.querySelector("title").innerHTML = "选择收件地址";
        //隐藏标题栏右键
        AlipayJSOperation.setRightButtonStatus(false);
        //设置标题
        AlipayJSOperation.setTitle('选择收件地址');
        //设置标题颜色
        AlipayJSOperation.setBarColor('#2FB3FE');

        //后退
        AlipayJSOperation.setLeftButtonStatus(() => {
            SendCxytjMessage.sendMessage('insepection_addresslist_back')
        });

        this.addressListFun() // 请求：用户车辆列表

        SendCxytjMessage.sendMessage('inspection_chooseaddress_init');
    }


    /*
    * 事件
    */

    /**
     * 请求用户地址
     */
    addressListFun() {
        let postData = {}
        Toast.hide(); //加载前 先关闭其他加载中的提示框 避免提示框一直存在的bug
        Toast.loading("", 30, () => Toast.info("网络错误", 2));
        getDataService.addressList(postData).then(resultData => {
            if (resultData.code == 1000) {
                //	console.log(resultData.data)
                // validFlag =是否置灰的判断标记，0灰置,1有效（广东省内）,2未知
                Toast.hide(); //加载前 先关闭其他加载中的提示框 避免提示框一直存在的bug
                //  let dataList = this.state.dataList;
                //dataList.push(...data);//ES6 合并数组新写法
                this.setState({
                    dataList: resultData.data.addressList,
                })
                // 没有车辆信息，跳转到新增车辆页面
                if (!resultData.data.addressList.length && location.href.indexOf('addressList') >= 0) {
                    //Toast.info('无可选地址', 3);
                    history.go(-1);
                    /* setTimeout(() => {
                         location.href.indexOf('addressList') >= 0 && history.go(-1)
                     }, 2000)*/
                    //this.context.router.push('addAddress/' + this.payTypeData)
                }


            }
            else {
                Toast.info(resultData.msg, 2);
            }
        });
    }

    //选择的选项
    getDataFUN(type) {
        SendCxytjMessage.sendMessage('insepection_addrlist_change');
        this.setState({
            type: type,
        });
        history.go(-1); //点击返回
        return false;
    }

    /**
     * ＋添加新地址 按钮
     * @param {*} url
     */
    addUrl(url) {
        SendCxytjMessage.sendMessage('insepection_addrlist_add');
        if (this.state.dataList.length == 5) {
            Toast.info('不能超过5个收货地址,添加失败', 1)
        } else {
            this.context.router.push(url);
        }
    }

    /*
    组件
    */

    //ifGray :true 表示 置灰；false 表示不置灰，可选
    render() {
//alert('===='+JSON.stringify(this.state.dataList));
        return (
            <div>
                <PageBar title="选择收件地址"/>
                <div className={style.box_List}>
                    {
                        this.state.dataList.map((e, i) =>
                            <Address key={i}
                                     index={i}
                                     fn={this.state.type}
                                     payTypeData={this.payTypeData}
                                     ifGray={this.payTypeData == 'ems' && e.validFlag == 0 ? true : false}

                                     orderId={this.orderId}
                                     addressId={e.addressId}
                                     name={e.name}
                                     phone={e.phone}
                                     addr={e.provinceName + e.cityName + e.areaName + e.location}
                                     onType={(data) => this.getDataFUN(data)}/>
                        )
                    }
                </div>

                {this.payTypeData == 'ems' &&
                <div className=' color999 plr30 ptb30 font-26 text-center' style={{'paddingBottom': '60px'}}>
                    <span className={style.iconI}>您选择的邮政上门取件，仅支持广东省内地址</span>
                </div>}
                <div className={style.box_List}>
                    <div onClick={() => this.addUrl('addAddress/' + this.orderId + '/' + this.payTypeData + '/noId')}
                         className={style.btn_Addto}>＋添加新地址
                    </div>
                </div>
            </div>
        )
    }
}

//使用context
AddressList.contextTypes = {
    router: React.PropTypes.object.isRequired
};

AddressList.defaultProps = {};

export default connect()(AddressList)